package br.jm.i18n;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.text.MessageFormat;
import java.util.Locale;

import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;

public final class I18NRepository {
	final MessageProvider globalProvider;

	public I18NRepository() {
		this(null);
	}

	public I18NRepository(final MessageProvider globalProvider) {
		this.globalProvider = globalProvider;
	}

	MessageProvider getProvider(final Path classFile, final Locale loc) throws IOException {
		return globalProvider == null ? new ResourceBundleMessageProvider(classFile, loc) : globalProvider;
	}

	public void spin(final Path path, final Locale loc) {
		try (InputStream is = Files.newInputStream(path)) {
			final String className = path.getFileName().toString().replace(".class", "");
			final Path target = path.resolveSibling(MessageFormat.format("{0}_{1}.class", className, loc));

			Files.deleteIfExists(target);
			Files.createFile(path);

			final ClassReader cr = new ClassReader(is);
			final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
			final MessageProvider mp = getProvider(path, loc);
			final I18NGenerator gen = new I18NGenerator(cw, mp, loc);

			cr.accept(gen, ClassReader.SKIP_DEBUG);

			final byte[] bc = cw.toByteArray();

			Files.write(target, bc);
		} catch (final IOException e) {
			throw new RuntimeException(e);
		}
	}
}
